<route lang="json5">
{
  style: {
    navigationStyle: 'default',
    navigationBarTitleText: '农事财务记录',
  },
}
</route>

<template>
  <view class="header-top">
    <view class="header-title" @click="showYear = true">
      <view>{{ selectedYear }}年</view>
      <wd-icon name="calendar" color="#999999" size="14px"></wd-icon>
    </view>
    <view class="header-content">
      <view class="content-left">本年度支出金额:</view>
      <view class="content-right">¥ {{ totalAmount }}</view>
    </view>
  </view>
  <view class="content-warp">
    <view class="content-tab">
      <view
        @click="tagClick(item, index)"
        v-for="(item, index) in DataList"
        :key="index"
        class="w-1/5 box-border p-1"
      >
        <view
          class="w-full h-[35px] rounded bg-white text-center leading-[35px] text-[14px] text-[#666666]"
          :class="active === item.id ? 'active' : ''"
        >
          {{ item.name }}
        </view>
      </view>
    </view>
  </view>
  <view class="content-form">
    <template v-for="(item, index) in descList" :key="index">
      <!--      <view-->
      <!--        v-if="index > 0"-->
      <!--        style="transform: rotate(45deg)"-->
      <!--        class="absolute top-[-10px] right-[-10px] z-[50px]"-->
      <!--      >-->
      <!--        <image-->
      <!--          src="@/static/images/plus.png"-->
      <!--          mode="widthFix"-->
      <!--          class="w-5"-->
      <!--          @click="removeRecord(item.id)"-->
      <!--        ></image>-->
      <!--      </view>-->
      <view @click="activeIndex = index">
        <view class="form-content">
          <view class="form-content-left">
            <text class="ismust">*</text>
            <text>农事时间</text>
          </view>
          <view class="form-content-right" @click="showDate = true">
            <view class="">{{ selectedDate }}</view>
            <wd-icon name="calendar" color="#999999" size="20px"></wd-icon>
          </view>
        </view>
        <view class="form-content">
          <view class="form-content-left">
            <text>当日天气</text>
          </view>
          <view class="form-content-right">
            <!--            <view class="">{{ weatherInfo }}</view>-->
            <wd-input v-model="weatherInfo" no-border></wd-input>
          </view>
        </view>
        <view class="flex justify-end">
          <image
            :src="
              activeIndex === index ? '/static/images/plus-fill.png' : '/static/images/plus.png'
            "
            mode="widthFix"
            class="w-5"
            @click="addRecord"
          ></image>
        </view>
        <view class="form-content">
          <view class="form-content-left">
            <text class="ismust">*</text>
            <text>所花费用</text>
          </view>
          <view class="form-content-right" style="padding: 0">
            <!--        <view class="button" @click="fee&#45;&#45;">-</view>-->
            <!--        <view class="center">{{ fee }}</view>-->
            <!--        <view class="button" @click="fee++">+</view>-->
            <wd-input-number v-model="item.amount" :min="0" @change="feeChange" />
          </view>
        </view>
        <view class="form-content" style="border-bottom: 1px solid #e5e5e5">
          <view class="form-content-left">
            <text>农事说明</text>
          </view>
          <view class="form-content-right-text">
            <wd-textarea
              auto-height
              custom-class="wd-textarea-warp"
              :maxlength="100"
              v-model="item.describe"
            />
            <view class="form-content-right-input">
              <view class="font-limet">{{ item.describe?.length }}/100</view>
              <view class="clear" @click="item.describe = ''">清除</view>
            </view>
          </view>
        </view>
      </view>
    </template>
  </view>
  <view class="button-warp" @click="goTotalTable">
    <view class="button">查看汇总表格</view>
  </view>
  <wd-action-sheet v-model="showYear" title="" @close="closeYear">
    <view
      class="cancel-btn pos-absolute top-5 left-5 z-[50] text-[#165DFF]"
      @click.stop="closeYear"
    >
      取消
    </view>
    <view
      class="confirm-btn pos-absolute top-5 right-5 z-[50] text-[#165DFF]"
      @click.stop="confirmYear"
    >
      确定
    </view>
    <wd-datetime-picker-view type="year" v-model="year" label="年" @change="yearChange" />
  </wd-action-sheet>
  <wd-action-sheet v-model="showDate" title="" @close="closeDate">
    <view
      class="cancel-btn pos-absolute top-5 left-5 z-[50] text-[#165DFF]"
      @click.stop="closeDate"
    >
      取消
    </view>
    <view
      class="confirm-btn pos-absolute top-5 right-5 z-[50] text-[#165DFF]"
      @click.stop="confirmDate"
    >
      确定
    </view>
    <wd-datetime-picker-view type="date" v-model="farmingDate" label="年" @change="dateChange" />
  </wd-action-sheet>
</template>

<script setup lang="ts">
import { recordSubmit, recordSummary, recordType, recordYearAmount } from '@/service/record'
import { formatDate } from '@/utils'
import { weather } from '@/service/need'
// eslint-disable-next-line import/extensions
import amap from '@/utils/amap-wx.130.js'
import { useToast } from 'wot-design-uni'

const active = ref(0)
const value14 = ref('灌溉')

// 选择年份
const year = ref(Date.now())
const selectedYear = ref(new Date().getFullYear())
const showYear = ref(false)
const confirmYear = () => {
  selectedYear.value = new Date(year.value).getFullYear()
  getTotalAmount()
  showYear.value = false
}
const closeYear = () => {
  showYear.value = false
}
const yearChange = ({ value }) => {
  console.log(value, 'yearChange')
}
// 选择日期
const farmingDate = ref(Date.now())
const showDate = ref(false)
const selectedDate = ref<string>(formatDate(Date.now(), 'yyyy-MM-dd'))
const closeDate = () => {
  showDate.value = false
}
const confirmDate = () => {
  selectedDate.value = formatDate(farmingDate.value, 'yyyy-MM-dd')
  showDate.value = false
}
const dateChange = ({ value }) => {
  console.log(value, 'dateChange')
}
// 所花费用
const fee = ref(0)
const feeChange = ({ value }) => {
  console.log(value, 'feeChange')
}
function goChooseYear() {
  uni.navigateTo({
    url: './selectYear/index',
  })
}
function goChooseDete() {
  uni.navigateTo({
    url: './selectDate/index',
  })
}
// 天气
const weatherInfo = ref('') // 18℃ 多云转晴
const myAmapFun = ref(null)
const getWeather = () => {
  myAmapFun.value.getRegeo({
    success: async function (data) {
      // 成功回调
      const city = data[0].regeocodeData.addressComponent.city
      const res: IResData<any> = await weather(city)
      console.log(res, '天气')
      if (res.code === 1) {
        weatherInfo.value = `${res.data.temperature}℃ ${res.data.weather}`
        descList.value[0].weather = weatherInfo.value
      }
      // console.log(city, '位置信息')
    },
    fail: function (info) {
      // 失败回调
      console.log(info)
    },
  })
}
// 农事花费记录
const activeIndex = ref(0)
const descList = ref<IRecordChildren[]>([
  {
    date: selectedDate.value,
    weather: '',
    amount: 0,
    describe: '灌溉',
  },
])
const addId = ref(1)
const addRecord = () => {
  activeIndex.value = descList.value.length
  descList.value.push({
    date: selectedDate.value,
    weather: weatherInfo.value,
    amount: 0,
    describe: '',
  })
  addId.value++
}
const removeRecord = (id: number) => {
  descList.value = descList.value.filter((item) => item.id !== id)
}
const DataList = ref<IRecordType[]>([])
const tagClick = (item, index) => {
  active.value = item.id
  descList.value[activeIndex.value].describe = item.name
}
const getRecordType = async () => {
  const res: IResData<IRecordType[]> = await recordType()
  if (res.code === 1) {
    DataList.value = res.data
    active.value = res.data[0]?.id
  }
}
async function goTotalTable() {
  // summaryParams.year = `${selectedYear.value}`
  // getRecordSummary()
  const total = descList.value
    .map((item) => item.amount)
    .reduce((sum, cur) => parseFloat(sum) + parseFloat(cur), 0)
  if (total === 0) {
    return await uni.navigateTo({
      url: `./totalTable/index?year=${selectedYear.value}`,
    })
  }
  const params: IRecordSubmit = {
    id: active.value,
    sub_data: JSON.stringify(descList.value),
    // date: selectedDate.value,
    // amount: '100',
    // weather: '3℃ 晴',
    // describe: '灌溉',
  }
  const res: IResData<any> = await recordSubmit(params)
  if (res.code === 1) {
    await uni.navigateTo({
      url: `./totalTable/index?year=${selectedYear.value}`,
    })
  }
}
// 年度支出总金额
const totalAmount = ref(0)
const getTotalAmount = async () => {
  const res: any = await recordYearAmount(selectedYear.value)
  if (res.code === 1) {
    console.log(res, '总金额')
    totalAmount.value = res.data
  }
}
const toast = useToast()
onLoad(async () => {
  await getRecordType()
  myAmapFun.value = new amap.AMapWX({ key: import.meta.env.VITE_GD_KEY }) // 初始化高德地图sdk
  getWeather()
  descList.value[0].describe = DataList.value[0].name
  await getTotalAmount()
  if (uni.getAppAuthorizeSetting().locationAuthorized !== 'authorized') {
    toast.warning('未开启定位权限，可能会影响部分页面展示效果')
    uni.getLocation({
      type: 'gcj02',
      success: function (res) {},
      fail: function (info) {
        toast.error('获取定位权限失败，请重试')
      },
    })
  }
})
onShow(() => {
  getTotalAmount()
})
</script>

<style scoped lang="scss">
.header-top {
  // width: 100%;
  height: 101px;
  opacity: 1;
  background: #ffffff;
  padding: 10px 15px;
  padding-bottom: 0px;

  .header-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px;
    border-radius: 8px;
    opacity: 1;
    background: #f7f7f7;
    font-family: Source Han Sans;
    font-size: 15px;
    font-weight: normal;
    line-height: 26px;
    text-align: center;
    display: flex;
    align-items: center;
    letter-spacing: 0px;
    color: #666666;
  }

  .header-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px;

    .content-left {
      font-family: Source Han Sans;
      font-size: 12px;
      font-weight: normal;
      line-height: 26px;
      text-align: center;
      display: flex;
      align-items: center;
      letter-spacing: 0px;
      color: #666666;
    }

    .content-right {
      font-family: D-DIN;
      font-size: 20px;
      font-weight: bold;
      line-height: 26px;
      text-align: center;
      display: flex;
      align-items: center;
      letter-spacing: 0px;
      color: #56b756;
    }
  }
}

.content-warp {
  opacity: 1;
  background: #f7f7f7;

  .content-tab {
    display: flex;
    flex-wrap: wrap;
    padding: 10px 15px;

    //view {
    //  width: 65px;
    //  height: 33px;
    //  border-radius: 4px;
    //  opacity: 1;
    //  background: #ffffff;
    //  display: flex;
    //  align-items: center;
    //  justify-content: center;
    //  font-size: 14px;
    //  font-weight: normal;
    //  line-height: 20px;
    //  letter-spacing: 0px;
    //  color: #666666;
    //  margin-right: 5px;
    //  margin-top: 5px;
    //}
    //
    //view:nth-child(5) {
    //  margin-right: 0px;
    //}
    //
    //view:nth-child(10) {
    //  margin-right: 0px;
    //}

    .active {
      border-radius: 4px;
      opacity: 1;
      background: #56b756;
      color: #ffffff;
    }
  }
}

.content-form {
  background-color: #fff;
  padding-bottom: 50px;
  .form-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px;
    position: relative;
    .form-content-left {
      .ismust {
        color: red;
      }
    }

    .form-content-right-text {
      width: 225px;
      border: 1px solid rgba(153, 153, 153, 0.3);
      border-radius: 8px;
      min-height: 65px;
      padding: 4px;

      .wd-textarea-warp {
        // height: 65px;
      }

      .wd-textarea-warp::after {
        height: 0px;
      }
      .form-content-right-input {
        display: flex;
        justify-content: space-between;
        margin-top: 20px;
        .font-limet {
          font-family: Source Han Sans;
          font-size: 10px;
          font-weight: normal;
          line-height: 22px;
          text-align: center;
          display: flex;
          align-items: center;
          letter-spacing: 0.32px;
          font-variation-settings: 'opsz' auto;
          color: #666666;
        }
        .clear {
          font-family: Source Han Sans;
          font-size: 12px;
          font-weight: normal;
          line-height: 22px;
          text-align: center;
          display: flex;
          align-items: center;
          letter-spacing: 0.32px;
          font-variation-settings: 'opsz' auto;
          color: #56b756;
        }
      }
    }

    .form-content-right {
      display: flex;
      align-items: center;
      width: 225px;
      height: 32px;
      justify-content: space-between;
      opacity: 1;
      box-sizing: border-box;
      border: 1px solid rgba(153, 153, 153, 0.3);
      border-radius: 8px;
      padding: 10px;
      font-family: Source Han Sans;
      font-size: 15px;
      font-weight: normal;
      line-height: 22px;
      text-align: center;
      display: flex;
      align-items: center;
      letter-spacing: 0.32px;
      font-variation-settings: 'opsz' auto;
      color: #333333;

      .button {
        width: 36px;
        height: 32px;
        border-radius: 4px;
        font-size: 20px;
        opacity: 1;
        background: #f7f7f7;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 -11px;
      }

      .center {
        flex: 1;
      }
    }
  }
}

.button-warp {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  text-align: center;
  padding: 12px 15px;
  background-color: #fff;
  z-index: 10;
  .button {
    border-radius: 4px;
    opacity: 1;
    background: #56b756;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
  }
}
:deep(.wd-input-number) {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}
:deep(.wd-input-number__action) {
  height: 100% !important;
  width: 50px !important;
  background: #f7f7f7 !important;
}
:deep(.wd-input-number__inner) {
  width: calc(100% - 100px);
  height: 100%;
  input {
    height: 100%;
    width: 100%;
  }
}
</style>
